import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: {
      title: '首页',
      keepAlive: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Auth/Login.vue'),
    meta: {
      title: '登录',
      hideNavBar: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Auth/Register.vue'),
    meta: {
      title: '注册',
      hideNavBar: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile/index.vue'),
    meta: {
      title: '个人中心',
      requiresAuth: true
    }
  },
  {
    path: '/profile/edit',
    name: 'ProfileEdit',
    component: () => import('@/views/User/Profile.vue'),
    meta: {
      title: '编辑资料',
      requiresAuth: true,
      hideNavBar: true
    }
  },
  {
    path: '/upload',
    name: 'Upload',
    component: () => import('@/views/Upload/index.vue'),
    meta: {
      title: '发布视频',
      requiresAuth: true,
      hideNavBar: true
    }
  },
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: () => import('@/views/User/index.vue'),
    meta: {
      title: '用户主页'
    }
  },
  {
    path: '/video/:id',
    name: 'VideoDetail',
    component: () => import('@/views/Video/Detail.vue'),
    meta: {
      title: '视频详情',
      hideNavBar: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error/404.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = `${to.meta.title} - 我的抖音`
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.token) {
      // 未登录，跳转到登录页
      next({
        name: 'Login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 如果有token但没有用户信息，尝试获取用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.fetchUserInfo()
      } catch (error) {
        // 获取用户信息失败，清除token并跳转到登录页
        userStore.logout()
        next({
          name: 'Login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }
  }
  
  // 如果已登录用户访问登录/注册页，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && userStore.isLoggedIn) {
    next({ name: 'Home' })
    return
  }
  
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 页面切换完成后的处理
  // 可以在这里添加页面统计等逻辑
})

export default router 